package gui;

import java.awt.Dimension;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.border.BevelBorder;

import person.DayPlan;
import person.Interval;
import person.Person;
import person.PersonAchive;
import personInfo.PersonTableModel;

public class PersonListPopupMenu {
	private JMenuItem editPerson;
	private Person p;
	private JPopupMenu PersonPopup;
	private JMenuItem removePerson;

	public PersonListPopupMenu(Person pe) {
		p = pe;
	}

	private JMenuItem getEditPerson(final FamilyDialog FD) {
		if (editPerson == null) {
			editPerson = new JMenuItem();
			editPerson.setText("Edit " + p.getName());
			editPerson.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					FD.getAddMemberDialog();
					FD.setData(p);
					if (p.getPlan() != null) {
						updadatePlan(p.getPlan(), FD);
						FD.AddMemberDialog.setSize(440, 482);
						FD.scheduleCB.setSelected(true);
						FD.MemberSchedule.setEnabled(true);
					} else {
						PersonTableModel pm=(PersonTableModel)FD.ScheduleTable.getModel();
						pm.clearModel();

						FD.MemberSchedule.setEnabled(false);
						FD.scheduleCB.setSelected(false);
						FD.AddMemberDialog.setSize(440, 277);
					}
					FD.Add.setText("Save");
					FD.AddMemberDialog.setVisible(true);
					FD.setEnabled(false);
				}

				private void updadatePlan(DayPlan dp, FamilyDialog fD) {
					for (int i = 0; i < fD.ScheduleTable.getRowCount(); i++) {
						Interval iv = dp.getInterval((String) fD.ScheduleTable
								.getValueAt(i, 0));
						if (iv != null) {
							fD.ScheduleTable.setValueAt(iv.getStart(), i, 1);
							fD.ScheduleTable.setValueAt(iv.getEnd(), i, 2);
							fD.ScheduleTable.setValueAt(Boolean.TRUE, i, 3);
						}
					}

				}
			});
		}
		return editPerson;
	}

	/**
	 * This method initializes AddObject
	 * 
	 * @return javax.swing.JMenuItem
	 */
	private JMenuItem getRemovePerson(final FamilyDialog FD) {
		if (removePerson == null) {
			removePerson = new JMenuItem();
			removePerson.setText("Remove " + p.getName());
			removePerson.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					PersonAchive.remove(p.getName(), p.getLastName());
					FD.refreshList();
					FD.MemberList.repaint();
				}
			});
		}
		return removePerson;
	}

	public JPopupMenu getRoomPopUp(FamilyDialog FD) {
		if (PersonPopup == null) {
			PersonPopup = new JPopupMenu();
			PersonPopup.setSize(new Dimension(80, 120));
			PersonPopup.add(getRemovePerson(FD));
			PersonPopup.add(getEditPerson(FD));
			PersonPopup.setBorder(new BevelBorder(BevelBorder.RAISED));

		}
		return PersonPopup;
	}

}
